package com.zaofan.dao;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.zaofan.bean.OpenArea;
import com.zaofan.bean.OpenCity;
import com.zaofan.bean.Shop;
import com.zaofan.dao.base.DaoSupportImpl;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.SqlBuilderUtils;

public class ShopDao extends DaoSupportImpl<Shop> {

	public void setShopState(Shop shop) {
		try {
			String sql = "update " + Shop.class.getSimpleName().toLowerCase() + " set state = " + shop.getState()
					+ " where id = " + shop.getId();
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(getDataSource());
			runner.update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public Integer addShop(Shop shop) {
		Connection conn = C3p0DataSourceUtils.getConnection();
		int id = 0;
		try {
			String sql = SqlBuilderUtils.builderInsertSql(Shop.class, shop);
			System.err.println(sql);
			QueryRunner runner = new QueryRunner();
			runner.update(conn, sql);
			// 获取新增记录的自增主键
			try {
				Long t = (Long) runner.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler<Long>());
				id = t.intValue();
			} catch (Exception e) {
				BigInteger t = (BigInteger) runner.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler<BigInteger>());
				id = t.intValue();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return id;
	}

	public void updateAreaName(OpenArea openArea) {
		try {
			String sql = "update " + Shop.class.getSimpleName().toLowerCase() + " set areaName = '"
					+ openArea.getAreaName() + "' where areaId = " + openArea.getId();
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(getDataSource());
			runner.update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void updateCityName(OpenCity openCity) {
		try {
			String sql = "update " + Shop.class.getSimpleName().toLowerCase() + " set cityName = '"
					+ openCity.getCityName() + "' where cityId = " + openCity.getId();
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(getDataSource());
			runner.update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}
